<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="支付单号" prop="paymentNumber">
          <el-input
            v-model="queryParams.paymentNumber"
            placeholder="请输入支付单号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNumber">
          <el-input
            v-model="queryParams.orderNumber"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="支付状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="支付状态" clearable style="width: 200px">
            <el-option label="待支付" value="PENDING" />
            <el-option label="支付成功" value="SUCCESS" />
            <el-option label="支付失败" value="FAILED" />
            <el-option label="已退款" value="REFUNDED" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="queryParams.paymentMethod" placeholder="支付方式" clearable style="width: 200px">
            <el-option label="微信支付" value="WECHAT" />
            <el-option label="支付宝" value="ALIPAY" />
            <el-option label="银行卡" value="BANK_CARD" />
            <el-option label="余额支付" value="BALANCE" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="6">
        <div class="stat-card">
          <div class="stat-icon success">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">¥{{ statistics.totalAmount || 0 }}</div>
            <div class="stat-label">总交易金额</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="6">
        <div class="stat-card">
          <div class="stat-icon primary">
            <el-icon><List /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ statistics.totalCount || 0 }}</div>
            <div class="stat-label">总交易笔数</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="6">
        <div class="stat-card">
          <div class="stat-icon warning">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ statistics.pendingCount || 0 }}</div>
            <div class="stat-label">待支付订单</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="6">
        <div class="stat-card">
          <div class="stat-icon danger">
            <el-icon><RefreshLeft /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">¥{{ statistics.refundAmount || 0 }}</div>
            <div class="stat-label">退款金额</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="RefreshLeft"
            :disabled="multiple"
            @click="handleRefund"
          >退款</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 支付记录表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="paymentList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="支付单号" align="center" prop="paymentNumber" width="180" />
        <el-table-column label="订单号" align="center" prop="orderNumber" width="180" />
        <el-table-column label="用户信息" align="center" width="120">
          <template #default="scope">
            <div>
              <div>{{ scope.row.username }}</div>
              <div class="text-muted">{{ scope.row.userPhone }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="支付金额" align="center" width="120">
          <template #default="scope">
            <span class="amount-text">¥{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getPaymentMethodType(scope.row.paymentMethod)">
              {{ getPaymentMethodText(scope.row.paymentMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="第三方单号" align="center" prop="thirdPartyNumber" width="180" />
        <el-table-column label="支付时间" align="center" prop="paymentTime" width="180">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.paymentTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              icon="View"
              @click="handleView(scope.row)"
              link
            >查看</el-button>
            <el-button
              v-if="scope.row.status === 'SUCCESS'"
              type="warning"
              icon="RefreshLeft"
              @click="handleRefund(scope.row)"
              link
            >退款</el-button>
            <el-button
              v-if="scope.row.status === 'PENDING'"
              type="success"
              icon="Check"
              @click="handleConfirm(scope.row)"
              link
            >确认</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 退款对话框 -->
    <el-dialog
      v-model="refundDialog.visible"
      title="申请退款"
      width="500px"
    >
      <el-form :model="refundDialog.form" label-width="100px">
        <el-form-item label="退款金额">
          <el-input-number
            v-model="refundDialog.form.refundAmount"
            :max="refundDialog.maxAmount"
            :min="0.01"
            :precision="2"
            style="width: 100%"
          />
          <div class="form-tip">最大可退款金额: ¥{{ refundDialog.maxAmount }}</div>
        </el-form-item>
        <el-form-item label="退款原因">
          <el-select v-model="refundDialog.form.refundReason" placeholder="请选择退款原因">
            <el-option label="用户申请退款" value="USER_REQUEST" />
            <el-option label="商品质量问题" value="QUALITY_ISSUE" />
            <el-option label="发货错误" value="SHIPPING_ERROR" />
            <el-option label="其他原因" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款说明">
          <el-input
            v-model="refundDialog.form.refundDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入退款说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund" :loading="refundDialog.loading">确定退款</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getPaymentPage, 
  getPaymentStatistics,
  refundPayment,
  confirmPayment,
  exportPayments
} from '@/api/mall'
import { useRouter } from 'vue-router'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const paymentList = ref([])
const statistics = ref({})
const queryFormRef = ref()
const dateRange = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  paymentNumber: undefined,
  orderNumber: undefined,
  status: undefined,
  paymentMethod: undefined,
  startTime: undefined,
  endTime: undefined
})

// 退款对话框
const refundDialog = reactive({
  visible: false,
  loading: false,
  paymentId: null,
  maxAmount: 0,
  form: {
    refundAmount: 0,
    refundReason: '',
    refundDescription: ''
  }
})

// 获取支付记录列表
const getList = async () => {
  loading.value = true
  try {
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }
    
    const response = await getPaymentPage(queryParams)
    if (response.code === 200) {
      paymentList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取支付记录失败')
    }
  } catch (error) {
    console.error('获取支付记录失败:', error)
    ElMessage.error('获取支付记录失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const response = await getPaymentStatistics()
    if (response.code === 200) {
      statistics.value = response.data || {}
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看按钮操作
const handleView = (row) => {
  router.push(`/mall/payment/detail/${row.id}`)
}

// 退款按钮操作
const handleRefund = (row) => {
  const payment = row.id ? row : paymentList.value.find(item => ids.value.includes(item.id))
  if (!payment) {
    ElMessage.warning('请选择要退款的记录')
    return
  }
  
  refundDialog.paymentId = payment.id
  refundDialog.maxAmount = payment.amount
  refundDialog.form = {
    refundAmount: payment.amount,
    refundReason: '',
    refundDescription: ''
  }
  refundDialog.visible = true
}

// 确认退款
const confirmRefund = async () => {
  if (!refundDialog.form.refundReason) {
    ElMessage.warning('请选择退款原因')
    return
  }
  
  try {
    refundDialog.loading = true
    await refundPayment(refundDialog.paymentId, refundDialog.form)
    ElMessage.success('退款申请提交成功')
    refundDialog.visible = false
    getList()
    getStatistics()
  } catch (error) {
    console.error('退款失败:', error)
    ElMessage.error('退款失败')
  } finally {
    refundDialog.loading = false
  }
}

// 确认支付
const handleConfirm = async (row) => {
  try {
    await ElMessageBox.confirm(`确认支付单 ${row.paymentNumber} 已完成支付？`, '确认支付', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await confirmPayment(row.id)
    ElMessage.success('确认成功')
    getList()
    getStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认支付失败:', error)
      ElMessage.error('确认支付失败')
    }
  }
}

// 导出按钮操作
const handleExport = async () => {
  try {
    await exportPayments(queryParams)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 工具函数
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'SUCCESS': 'success',
    'FAILED': 'danger',
    'REFUNDED': 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'PENDING': '待支付',
    'SUCCESS': '支付成功',
    'FAILED': '支付失败',
    'REFUNDED': '已退款'
  }
  return textMap[status] || status
}

const getPaymentMethodType = (method) => {
  const typeMap = {
    'WECHAT': 'success',
    'ALIPAY': 'primary',
    'BANK_CARD': 'warning',
    'BALANCE': 'info'
  }
  return typeMap[method] || 'info'
}

const getPaymentMethodText = (method) => {
  const textMap = {
    'WECHAT': '微信支付',
    'ALIPAY': '支付宝',
    'BANK_CARD': '银行卡',
    'BALANCE': '余额支付'
  }
  return textMap[method] || method
}

// 页面加载时获取数据
onMounted(() => {
  getList()
  getStatistics()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.stats-row {
  margin-bottom: 16px;
  
  .stat-card {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 16px;
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      
      &.primary {
        background-color: #e1f3ff;
        color: #409eff;
      }
      
      &.success {
        background-color: #e1f9e1;
        color: #67c23a;
      }
      
      &.warning {
        background-color: #fdf6ec;
        color: #e6a23c;
      }
      
      &.danger {
        background-color: #fef0f0;
        color: #f56c6c;
      }
    }
    
    .stat-content {
      flex: 1;
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .stat-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}

.amount-text {
  color: #e6a23c;
  font-weight: bold;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
